import type {
  BaseStyleConfig,
  IPersonalizationItemConfig,
} from '../../../../types/interfaces'
import { RangeSlider } from '../../../../components/range_slider'
import { UserPref } from '../../../../lib/abstract'
import { VALID_RESULT } from '../../../../types/constants'

export class Image extends UserPref {
  readonly id = 'image'
  readonly name = 'Image'
  readonly styleConfigKey = 'image'
  readonly cssProperty = 'filter'
  readonly cssValueSuffix = ''

  constructor(config: IPersonalizationItemConfig) {
    super(config)
  }

  createComponent(config: BaseStyleConfig, value: string, _mode: string, debouncedSave: (() => void) & { flush: () => void }): RangeSlider {
    const id = this.generateId(config.styleVar)
    const remark = config.remark || ''
    return new RangeSlider({
      id,
      label: '图片亮度',
      value: Number(value) || 1,
      min: 0,
      max: 2,
      step: 0.01,
      title: remark,
      onChange: (value) => {
        this.cachedValues.set(id, String(value))
        debouncedSave()
      },
      showValue: true,
    })
  }

  // 由于直接使用的是 input[type="range"] 传递的值，所以不需要额外的校验逻辑
  handleCheck(value: string): { status: ValidResultType, error: string } {
    if (!value || value.length === 0)
      return { status: VALID_RESULT.SKIP.value, error: '' }
    return { status: VALID_RESULT.VALID.value, error: '' }
  }

  generateStyleRule(selector: string, value: string): string {
    // brightness 控制亮度（日常使用建议 0.3-2），contrast 控制对比度（日常使用建议 0.5-1.5）
    return `${selector} { ${this.cssProperty}: brightness(${value}${this.cssValueSuffix}) contrast(1.0) !important; }`
  }
}
